app.controller('HeaderCtrl', function ($scope, menu, appRoute) {
    $scope.menu = menu(appRoute);
});

app.controller('HomeCtrl', function ($scope, $http, $interval, toast) {
    function updateDiffTime() {
        for (var i = 0; i < $scope.list.length; i++) {
            var now = new Date().getTime();
            var diff = Math.ceil((now - $scope.list[i].lastRefresh) / 1000 / 60);
            if (diff <= 2) {
                $scope.list[i].ago = 'Just now';
            } else if (diff <= 59) {
                $scope.list[i].ago = diff + ' minutes ago';
            } else {
                $scope.list[i].ago = Math.ceil(diff / 60) + ' hours ago';
            }
        }
    }

    function updateStatus() {
        $http({ url: '/svc/Dashboard/OverAll', method: 'GET' }).then(function (result) {
            toast.push("Update success.");
            for (var i = 0; i < result.data.length; i++) {
                switch (result.data[i].status) {
                    case "Unknown":
                        result.data[i].displayStatus = "Unknown";
                        result.data[i].FrontType = "default";
                        result.data[i].BackType = "default";
                        break;
                    case "Alive":
                        result.data[i].displayStatus = "Alive";
                        result.data[i].FrontType = "success";
                        result.data[i].BackType = "success";
                        break;
                    case "Dead":
                        result.data[i].displayStatus = "Dead";
                        result.data[i].FrontType = "danger";
                        result.data[i].BackType = "danger";
                        break;
                    case "Unstable":
                        result.data[i].displayStatus = "Unstable";
                        result.data[i].FrontType = "warning";
                        result.data[i].BackType = "warning";
                        break;
                }                
            }
            $scope.list = result.data;
            updateDiffTime();
        }, function (err) {
            toast.push(err, 'danger');
        });
    }

    updateStatus();
    $interval(updateStatus, 60000);
    $interval(updateDiffTime, 10000);
});